/* eslint-disable @typescript-eslint/no-shadow */
import { nestedCityCode } from '@/components/assets/nestedCityCode';
import { LoadingOutlined } from '@ant-design/icons/lib/icons';
import type { ProFormInstance } from '@ant-design/pro-components';
import { ProCard } from '@ant-design/pro-components';
import {
  ProFormCascader,
  ProFormDigit,
  ProFormList,
  ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ProForm } from '@ant-design/pro-form/lib/layouts';
import { FooterToolbar } from '@ant-design/pro-layout';
import _ from 'lodash';
import { Button, Col, Collapse, message, Row } from 'antd';
import dayjs from 'dayjs';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useHistory, useModel } from 'umi';
import { optionsSchemeItem } from '../../park-charge/service';
import styles from '../index.less';
import { applyParkItem, gateCameraItem, getParkDetail, saveParkItem } from '../service';
import type { getParkDetails, ZoneForm } from '../types';
import { addParkBase } from '../utils';

const { Panel } = Collapse;

interface addProps {
  close: (e: boolean) => void;
  isSave: (e: boolean) => void;
  id?: string;
  tenant_id?: string;
}

export default (props: addProps) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const tenantId = currUser?.tenantId;
  const { close, isSave, id, tenant_id } = props;
  const history = useHistory();
  const secondRef = useRef();
  const formRef = useRef<ProFormInstance>();
  const [saveHint, setSaveHint] = useState<React.ReactNode>('草稿未保存');
  const [addParkDate, setAddParkDate] = useState<any>();
  const [formIsSave, setFormIsSave] = useState<boolean>(true);

  const [parkDetails, setParkDetails] = useState<getParkDetails>();

  useEffect(() => {
    getParkDetail(id!).then((res) => {
      if (res && res.code == 0) {
        setParkDetails(res.data);
      }
    });
  }, []);
  useEffect(() => {
    if (parkDetails) {
      const details = _.cloneDeep(parkDetails);
      delete details.schemeId;
      const gateChannels: any = details?.channels.map((item, index) => {
        delete item.masterCamera?.cameraId;
        delete item.secondCamera?.cameraId;
        delete item.autoRelease;
        delete item.releaseMode;
        return {
          ...item,
        };
      });
      formRef.current?.setFieldsValue({
        ...details,
        maxLeaveTime: parkDetails.maxLeaveTime || '',
        spaceTotalCount: parkDetails.spaceTotalCount || '',
        spaceCount: parkDetails.spaceCount || '',
        schemeId: parkDetails?.schemeId
          ? { value: parkDetails?.schemeId, label: parkDetails?.schemeName }
          : '',
        addressCode: getCityArray(String(parkDetails?.addressCode)),
        gateChannels: gateChannels ? gateChannels : [{}],
      });
      setTimeout(() => {
        setAddParkDate(formRef.current?.getFieldsValue());
      }, 1);
    }
  }, [parkDetails]);
  function getCityArray(code: string) {
    // const code = parkDetails?.addressCode ? parkDetails?.addressCode : 0;
    if (code == undefined || code == '0' || code == 'null' || code == '') {
      return;
    }
    if (String(code).endsWith('0000')) {
      return [];
    } else if (!String(code).endsWith('0000') && String(code).endsWith('00')) {
      const city = code.substring(0, 4) + '00';
      return [city, code];
    } else if (!String(code).endsWith('0000') && !String(code).endsWith('00')) {
      const province = code.substring(0, 2) + '0000';
      const city1 = code.substring(0, 4) + '00';
      if (
        code.startsWith('31') ||
        code.startsWith('50') ||
        code.startsWith('11') ||
        code.startsWith('12')
      ) {
        return [province, code];
      } else {
        return [province, city1, code];
      }
    }
    return '-';
  }
  const handleConfirm = useCallback((message: string, callback) => {
    if (window.confirm(message)) {
      callback(true);
      return true;
    } else {
      callback(false);
      return false;
    }
  }, []);
  useEffect(() => {
    if (addParkDate == undefined && formRef.current?.getFieldsValue() != undefined) {
      setAddParkDate(formRef.current?.getFieldsValue());
    }
  }, [addParkDate]);
  useEffect(() => {
    // 周期性检测数据是否被修改
    const intervalId = setInterval(() => {
      // 判断数据是否被修改
      if (JSON.stringify(formRef.current?.getFieldsValue()) !== JSON.stringify(addParkDate)) {
        setFormIsSave(false);
        isSave(false);
      } else {
        setFormIsSave(true);
        isSave(true);
      }
    }, 500);
    return () => {
      clearInterval(intervalId);
    };
  }, [addParkDate, isSave]);
  useEffect(() => {
    const unblock = history.block((location, action) => {
      if (!formIsSave) {
        const res = handleConfirm('草稿还未保存,确定离开当前页面吗？', (result: any) => {
          if (result) {
            window.onbeforeunload = null;
            return true;
          }
          return result;
        });
        return res;
      }
    });
    return () => {
      unblock();
    };
  }, [history, handleConfirm, formIsSave]);
  useEffect(() => {
    if (!formIsSave) {
      window.onbeforeunload = function () {
        return 'Are you sure you want to leave?';
      };
    } else {
      window.onbeforeunload = null;
    }
  }, [formIsSave]);
  return (
    <>
      <ProForm<ZoneForm>
        formRef={formRef}
        submitter={{
          // 完全自定义整个区域
          render: (props, _doms) => {
            return [
              <FooterToolbar key="addFooterBar">
                {saveHint}
                <Button
                  style={{ marginLeft: 30 }}
                  key="rest"
                  onClick={async () => {
                    setSaveHint(
                      <>
                        <LoadingOutlined />
                        草稿保存中
                      </>,
                    );
                    const values: ZoneForm = formRef.current?.getFieldsValue();
                    console.log('values', values);

                    const res: any = await saveParkItem({
                      ...values,
                      gateChannels: values?.gateChannels?.map((item) => {
                        return {
                          ...item,
                          autoRelease: item.autoRelease && item.autoRelease.toString(),
                          releaseMode: item.releaseMode && item.releaseMode.toString(),
                        };
                      }),
                      addressCode:
                        values.addressCode && values.addressCode[values.addressCode.length - 1],
                      tenantId: tenant_id || tenantId,
                      schemeId:
                        (values.schemeId.value == null ? '' : values.schemeId.value) ||
                        values.schemeId,
                      id,
                    });
                    if (res) {
                      if (res.code === 0) {
                        setAddParkDate(values);
                        message.success('保存成功');
                        setSaveHint(<>已保存草稿 {dayjs().format('HH:mm:ss')}</>);
                      } else {
                        message.error(`保存失败 ${res.message}`);
                        setSaveHint(<>保存草稿失败 {dayjs().format('HH:mm:ss')}</>);
                      }
                    }
                  }}
                >
                  保存
                </Button>
                ,
                <Button type="primary" key="submit" onClick={() => props.form?.submit?.()}>
                  提交
                </Button>
              </FooterToolbar>,
            ];
          },
        }}
        onFinish={async (values) => {
          const res = await applyParkItem({
            ...values,
            gateChannels: values.gateChannels?.map((item) => {
              return {
                ...item,
                autoRelease: item.autoRelease?.toString(),
                releaseMode: item.releaseMode?.toString(),
              };
            }),
            addressCode: values.addressCode && values.addressCode[values.addressCode.length - 1],
            tenantId: tenant_id || tenantId,
            schemeId:
              (values.schemeId.value == null ? '' : values.schemeId.value) || values.schemeId,
            id,
          });
          if (res) {
            if (res.code === 0) {
              close(false);
              message.success('提交成功');
              return true;
            } else {
              message.error(`提交失败 ${res.message}`);
              return false;
            }
          }
          return false;
        }}
        title="添加停车场"
        // contextMenu="wwdawdawd"
      >
        <ProCard
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>基础设置</div>}
          className={styles.card}
          style={{ borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }}
          bordered={false}
        >
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'停车场名称'}
                name="name"
                rules={[{ required: true, message: '请输入停车场名称' }]}
                placeholder="请输入停车场名称"
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormDigit
                label={'最大超时离场时间（分钟）'}
                name="maxLeaveTime"
                rules={[{ required: true, message: '请输入最大超时离场时间' }]}
                placeholder="请输入最大超时离场时间"
              />
            </Col>
            <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
              <ProFormDigit
                label={'停车场总车位数'}
                name="spaceTotalCount"
                rules={[{ required: true, message: '请输入车场总车位数' }]}
                placeholder="请输入车场总车位数"
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormDigit
                label={'停车场可用车位数'}
                name="spaceCount"
                rules={[{ required: true, message: '请输入停车场可用车位数' }]}
                placeholder="请输入停车场可用车位数"
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormSelect
                showSearch
                label={'收费规则'}
                name="schemeId"
                fieldProps={{
                  style: {
                    width: '100%',
                  },
                }}
                // request={(params) => optionsSchemeItem(params)}
                params={{ page: 1, pageSize: 10 }}
                request={async (params, props) => {
                  const res = await optionsSchemeItem({
                    ...params,
                    name: props.text,
                    tenantId: Number(tenant_id || tenantId),
                  });
                  if (res)
                    return res.data.list.map((item: { id: any; name: any }, index: any) => {
                      return {
                        value: item.id,
                        label: item.name,
                      };
                    });
                }}
                debounceTime={300}
                placeholder="请选择收费规则"
                rules={[{ required: true, message: '请选择收费规则' }]}
              />
            </Col>
            <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
              <ProFormCascader
                label={'停车场地址'}
                name="addressCode"
                placeholder="请选择停车场地址"
                fieldProps={{
                  fieldNames: { label: 'name', value: 'code', children: 'children' },
                  showSearch: true,
                  options: nestedCityCode,
                }}
                rules={[{ required: true, message: '请选择停车场地址' }]}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'停车场联系人'}
                name="connectUser"
                placeholder="请填写停车场联系人"
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormText
                label={'停车场联系方式'}
                name="phone"
                placeholder="请填写停车场联系方式"
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24}>
              <ProFormTextArea
                label={'停车场简单描述'}
                name="desc"
                placeholder="请填写停车场简单描述"
              />
            </Col>
          </Row>
        </ProCard>
        <ProCard
          style={{ borderTopLeftRadius: 0, borderTopRightRadius: 0 }}
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>通道配置</div>}
          bordered={false}
        >
          {parkDetails && (
            <ProFormList
              creatorButtonProps={{
                creatorButtonText: '添加通道',
              }}
              name="gateChannels"
              // initialValue={[{}]}
              // actionGuard={{
              //   beforeAddRow: async (defaultValue, insertIndex, count) => {
              //     return new Promise((resolve) => {
              //       resolve(true);
              //       console.log(defaultValue?.name, insertIndex, count);
              //     });
              //   },
              // }}
              itemRender={({ listDom, action }, { record }) => {
                return (
                  <ProForm.Item noStyle>
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                      }}
                    >
                      {listDom}
                      {action}
                    </div>
                  </ProForm.Item>
                );
              }}
            >
              {(
                _meta, //当前行的基本信息
                index, //当前的行号
                _action, //操作行的快捷方法
                _count, //总行数
              ) => (
                <Collapse
                  style={{ marginBottom: 10 }}
                  collapsible="header"
                  defaultActiveKey={[
                    '0',
                    '1',
                    '2',
                    '3',
                    '4',
                    '5',
                    '6',
                    '7',
                    '8',
                    '9',
                    '10',
                  ]} /*  onChange={onChange} */
                >
                  <Panel header={`通道 ${index + 1}`} key={`${index}`}>
                    <Row gutter={16}>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormText
                          key={`q${index}`}
                          label={'通道名称'}
                          name="channelName"
                          rules={[{ required: true, message: '通道名称不能为空' }]}
                          placeholder="自定义通道名称"
                        />
                      </Col>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormRadio.Group
                          key={`w${index}`}
                          name="channelType"
                          label="通道类型"
                          options={addParkBase.channelType.map((item, index) => ({
                            value: index + 1,
                            label: item,
                          }))}
                          placeholder="请选择通道类型"
                          rules={[{ required: true, message: '请选择收费规则' }]}
                        />
                      </Col>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormSelect
                          options={addParkBase.releaseMode.map((item, index) => ({
                            key: String(index + 1),
                            value: String(index + 1),
                            label: item,
                          }))}
                          key={`e${index}`}
                          name="releaseMode"
                          fieldProps={{
                            mode: 'multiple',
                          }}
                          style={{ width: '100%' }}
                          label={`放行模式`}
                          initialValue={
                            parkDetails?.channels[index]
                              ? Number(parkDetails?.channels[index]?.releaseMode![0])
                                ? parkDetails?.channels[index].releaseMode?.split(',')
                                : undefined
                              : undefined
                          }
                          placeholder="选择通道放行模式（可多选）"
                          rules={[{ required: true, message: '请选择放行模式' }]}
                        />
                      </Col>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormSelect
                          options={addParkBase.autoRelease.map((item, index) => ({
                            key: String(index + 1),
                            value: String(index + 1),
                            label: item,
                          }))}
                          key={`approver${index}`}
                          fieldProps={{
                            mode: 'multiple',
                          }}
                          initialValue={
                            parkDetails?.channels[index]
                              ? Number(parkDetails?.channels[index]?.autoRelease![0])
                                ? parkDetails?.channels[index].autoRelease?.split(',')
                                : undefined
                              : undefined
                          }
                          style={{ width: '100%' }}
                          label={'放行规则'}
                          name="autoRelease"
                          rules={[{ required: true, message: '请选择通道放行规则' }]}
                          placeholder="选择通道放行规则（可多选）"
                        />
                      </Col>
                    </Row>
                    <Row gutter={16}>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormSelect
                          showSearch
                          initialValue={
                            parkDetails?.channels[index]
                              ? parkDetails?.channels[index]?.masterCamera?.cameraId
                                ? Number(parkDetails?.channels[index]?.masterCamera?.cameraId)
                                : ''
                              : ''
                          }
                          key={index + 'master'}
                          label={'主相机配置'}
                          name={['masterCamera', 'cameraId']}
                          params={{ page: 1, pageSize: 10 }}
                          request={async (params, props) => {
                            const res: any = await gateCameraItem({
                              ...params,
                              // name: props.text,
                              tenantId: Number(tenantId!),
                            });
                            if (res)
                              return res.data.list.map(
                                (item: { id: any; name: any }, index: any) => {
                                  return {
                                    value: item.id,
                                    label: item.name,
                                  };
                                },
                              );
                          }}
                          placeholder="请选择主相机"
                          rules={[
                            {
                              required: true,
                              message: '请选择主相机',
                            },
                          ]}
                        />
                      </Col>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormSwitch
                          name={['masterCamera', 'enable']}
                          label="是否启用主相机"
                          initialValue={true}
                          fieldProps={{
                            checkedChildren: '开启',
                            unCheckedChildren: '关闭',
                            defaultChecked: true,
                          }}
                        />
                      </Col>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormSelect
                          showSearch
                          fieldRef={secondRef}
                          key={index + 'second'}
                          label={'辅助相机配置'}
                          initialValue={
                            parkDetails?.channels[index]
                              ? parkDetails?.channels[index]?.secondCamera?.cameraId
                                ? Number(parkDetails?.channels[index]?.secondCamera?.cameraId)
                                : ''
                              : ''
                          }
                          name={['secondCamera', 'cameraId']}
                          params={{ page: 1, pageSize: 10 }}
                          request={async (params, props) => {
                            const res: any = await gateCameraItem({
                              ...params,
                              // name: props.text,
                              tenantId: Number(tenantId!),
                            });
                            if (res)
                              return res.data.list.map(
                                (item: { id: any; name: any }, index: any) => {
                                  return {
                                    value: item.id,
                                    label: item.name,
                                  };
                                },
                              );
                          }}
                          rules={[
                            {
                              required: true,
                              message: '请选择辅助相机配置',
                            },
                          ]}
                          placeholder="选择辅助相机"
                        />
                      </Col>
                      <Col lg={6} md={12} sm={24}>
                        <ProFormSwitch
                          initialValue={true}
                          name={['secondCamera', 'enable']}
                          label="是否启用辅助相机"
                          fieldProps={{
                            checkedChildren: '开启',
                            unCheckedChildren: '关闭',
                            defaultChecked: true,
                          }}
                        />
                      </Col>
                    </Row>
                  </Panel>
                </Collapse>
              )}
            </ProFormList>
          )}
        </ProCard>
      </ProForm>
    </>
  );
};
